package com.chare.config.security1;

import com.chare.Controller.LoginController;
import com.chare.config.Component.CustomFirter;
import com.chare.config.Component.CustomUrlDecisionManager;
import com.chare.config.Component.RestAccessDeniedHandler;
import com.chare.config.Component.RestAuthorizationEntryPoint;
import com.chare.pojo.Admin;
import com.chare.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import sun.plugin2.message.CustomSecurityManagerAckMessage;

import javax.annotation.Resource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Resource
    private LoginController loginController;
    @Autowired
    private RestAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private RestAuthorizationEntryPoint authorizationEntryPoint;
@Autowired
private IAdminService adminService;
@Autowired
private CustomUrlDecisionManager customUrlDecisionManager;
@Autowired
private CustomFirter customFilter;

    @Override

    protected  void configure(AuthenticationManagerBuilder auth)throws Exception
    {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());

    }



    //重写userDetailsService的登录方法
    @Override
    @Bean
    public UserDetailsService userDetailsService()
    {
        return username -> {
            Admin admin =adminService.getAdminByUserName(username);
            if(null!=admin){
                admin.setRoles(adminService.getRoles(admin.getId()));
                return new User(admin.getUsername(),admin.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin,taomeng"));
            }
            return null;



        };

    }
    //重写密码验证的方法
    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return  new BCryptPasswordEncoder();
    }
   @Override
   public void configure(WebSecurity web) throws Exception {
       web.ignoring().antMatchers(
               "/login",
               "/logout",
               "favicon.ico",
               "/doc.html",
               "/webjars/**",
               "/swagger-resources/**",
               "/v2/api-docs/**",
               "/captcha",
               "/ws/**",
               "/chat/**"
       );
   }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭防火墙
        http.csrf()
                .disable()
                //基于token,不需要session 关闭session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()

                //的拦截所有
                  .anyRequest()
                 .authenticated()
                //动态权限配置
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>()
                {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object)
                    {
                        object.setAccessDecisionManager(customUrlDecisionManager);
                        object.setSecurityMetadataSource(customFilter); return object;
                    } }
                    )
                .and()
                //关闭缓冲
                .headers()
                .cacheControl();
        //添加jwt  登录授权锅炉器
        http.addFilterBefore(jwtAuthencationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //自定义未授权和未登录结果返回
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler).authenticationEntryPoint(authorizationEntryPoint);

    }
    @Bean
    public JwtAuthencationTokenFilter jwtAuthencationTokenFilter(){
        return new JwtAuthencationTokenFilter();
    }
}
